<?php

namespace frontend\models;

use yii\base\Model;
use frontend\models\TbaMemberinfo;

class UserForm extends Model {
	//属性
	public $username;//用户名
	public $Pwd;//密码
	public $RePwd;//确认密码
	public $Email;//电子邮箱
	public $lName;//姓名
	public $Remark;//备注
	public $verifycode;//验证码
	public $remmber;//记住密码
	
	//规则
	public function rules(){
		return [
			//注册部分
			[['username','Pwd','RePwd','Email','lName'],'required','message'=>'{attribute}不能为空','on'=>'register'],
			['username','string','max'=>8,'min'=>3,'tooLong'=>'用户名最多8位','tooShort'=>'用户名最少3位','on'=>'register'],
			['username','unique','targetClass'=>TbaMemberinfo::className(),'targetAttribute'=>'username','message'=>'{attribute}已存在','on'=>'register'],
			['Pwd','string','max'=>15,'min'=>6,'tooLong'=>'密码最多15位','tooShort'=>'密码最少6位','on'=>'register'],
			['RePwd','compare','compareAttribute'=>'Pwd','message'=>'密码不一致','on'=>'register'],
			['Email','email','message'=>'邮箱格式不正确','on'=>'register'],			
			//登陆部分
			[['username','Pwd','verifycode'],'required','message'=>'{attribute}不能为空','on'=>'login'],
			['Pwd','validatorPassword','on'=>'login'],
			['verifycode','captcha','captchaAction'=>'user/captcha','message'=>'验证码错误','on'=>'login'],			
		];
	}
	//场景
	public function scenarios(){
		return [
			'register'=>['username','Pwd','RePwd','Email','lName','Remark'],
			'login'=>['username','Pwd','verifycode','remmber'],
			'update'=>['username','Pwd','Email','lName']
		];
	}
	
	//属性标签
	public function attributeLabels(){
		return [
			'username'=>'用户名',
			'Pwd'=>'密码',
			'RePwd'=>'确认密码',
			'Email'=>'电子邮箱',
			'lName'=>'姓名',
			'Remark'=>'备注',
			'verifycode'=>'验证码',
			'remmber'=>'记住密码'
						
		];
	}
	
	//自定义验证器，验证密码
	public function validatorPassword($attribute,$params){
		if(!$this->hasErrors()){
			$user=TbaMemberinfo::findOne(['username'=>$this->username]);
			if(!$user){
				return $this->addError($attribute,'没有此用户');
			}
			//对密码进行md5加密后截取第9位后边的12位数
			if($user->Pwd !=substr(md5(trim($this->Pwd.$user->auth_key)), 9,12)){
				return $this->addError($attribute,'密码错误');
			}
			
		}
	}
	
	//登陆
	 public function login(){
		$user=TbaMemberinfo::findOne(['username'=>$this->username]);
		//var_dump($user);打印查出的用户信息
		$lifeTime=($this->remmber)?3600:0;
		
		if(\Yii::$app->user->login($user,$lifeTime)){
			return true;
		}else{
			return false;
		}
	} 
	
}

?>